| Total Complexity | 3 |
| Total Lines | 19 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 0 | ||
| 1 | 9 | import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common'; |
|
| 3 | |||
| 4 | @Injectable() |
||
| 5 | 9 | export class TokenGuard implements CanActivate { |
|
| 6 | 20 | constructor(private tokensService: TokensService) {} |
|
| 7 | |||
| 8 | async canActivate(context: ExecutionContext): Promise<boolean> { |
||
| 9 | 3 | const request = context.switchToHttp().getRequest<Request>(); |
|
| 10 | |||
| 11 | 3 | const tokenId = request.headers['x-api-token']; |
|
| 12 | |||
| 13 | 3 | if (!tokenId) { |
|
| 14 | 1 | throw new UnauthorizedException('Token is required'); |
|
| 15 | } |
||
| 16 | |||
| 17 | 2 | try { |
|
| 18 | 2 | await this.tokensService.consume(tokenId); |
|
| 19 | 1 | return true; |
|
| 20 | } catch (error) { |
||
| 21 | 1 | throw new UnauthorizedException(error.message); |
|
| 22 | } |
||
| 25 |